package com.jingwei.service.springsecurity;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.jingwei.domain.User;
import com.jingwei.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 经纬
 * @description: 登录成功处理器
 * @since 2025/1/15 15:04
 */
@Service("loginSuccessHandler")
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //设置相应的编码格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //获取当前登录用户信息
        User principal = (User) authentication.getPrincipal();
        //生成token
        String jwt = JwtUtil.createJWT(JSON.toJSONString(principal));
        //设置响应头信息，将token返回给前端
        httpServletResponse.setHeader("Authorization", "Bearer " + jwt);

        httpServletResponse.getWriter().write("登录成功");

    }
}
